/* eslint-disable */ 
var appVersion = '1.5.1'
var isType=1
var count = 0
var state = {
  isReFlash: false,
  ping: 800
}
var array1 = ['',
  'BTC登录',
  'ETH登录',
  'EOS登录',
  'USDT登录']
var randcode = ''
var isLogin = false
var bigTimes = 100
var code = ''
var isSetTime = null
// var cacheFn = []
var isReSub = false // 提交后是否再次提交
var isNeedLoginUrl = ['https://www.bigwinner.vip', 'https://www.bigwinner.vip/']
var isNeedFlash = ['https://www.bigwinner.vip/index/user/index']
var dec = ''
var subMin = 0.002 // 最小提交数
var yue = 0
var touzi = ''
var isTrySub = false
var secretObj = {
  key:'nokey',
  subTime:0
}
// loginINfo
var loginInfo = {
  addr: '',
  type: '',
  auto: false
}
function initSecret(){
  var date =+(new Date()) 
  //&&+(new Date())-secretObj.subTime>
  if(!secretObj.subTime&&date-secretObj.subTime>60*1000*3){
    secretObj.key = date+Math.random();
    secretObj.subTime = 0;
  }
}
function clearSecret(){
  secretObj.subTime = 0
  secretObj.key='nokey'
}
function getYueFrom(cb){
  sendMes({
    action:'getYue'
  },function(response){
    if(response.state=='getYue:ok'){
      yue = response.yue
      touzi = response.touzi
      setLocal({'yue':response})
      cb(yue,touzi)
    }
  })
}
function getYue(cb){
  if(!yue){
    getLocal('yue',function(res){
      if(res.yue){
        yue = res.yue.yue
        touzi = res.yue.touzi
      }
      cb(yue,touzi)
    })
  }else{
    cb(yue,touzi)
  }
}
function getLoginInfo (cb) {
  if (loginInfo.addr && loginInfo.type) {
    cb && cb(loginInfo)
  } else {
    getLocal('loginInfo', function (res) {
      if (res.loginInfo) {
        loginInfo.addr = res.loginInfo.addr
        loginInfo.type = res.loginInfo.type
      }
      cb && cb(loginInfo)
    })
  }
}
function log (str) {
  // console.log(str)
}
function setLocal (obj) {
  chrome.storage.local.set(obj, function () {
    log('设置已保存')
  })
}
function getLocal (key, cb) {
  chrome.storage.local.get(key, function (res) {
    log('已取出')
    cb && cb(res)
  })
}
function rmLocal (key) {
  chrome.storage.local.remove(key, function (res) {
  })
}
function checkLogin (cb) {
  if (code) {
    _checkLogin(cb)
  } else {
    getLocal('localCode', function (res) {
      if (res.localCode) {
        code = res.localCode.code
        randcode = res.localCode.randcode
        _checkLogin(cb)
      } else {
        cb && cb(false)
      }
    })
  }
}
function _checkLogin (cb) {
  $.post('http://gold.bestsloth.top/api/GoldApi/chechkJs', {code: code || '', randcode: randcode,type:isType, v: appVersion}, function (res) {
    if (res.code != 200) {
      isLogin = false
      code = ''
      randcode = ''
      rmLocal('localCode')
    } else {
      isLogin = true
      dec = res.data
    }
    cb && cb(res.code == 200, dec)
  })
}
function addSubNum (type) {
  if(secretObj.key=='nokey'&&type==1){
    initSecret()
  }
  if((secretObj.key=='nokey'||secretObj.subTime<1)&&type==2){
    return
  }
  $.post('http://gold.bestsloth.top/api/GoldApi/subNum', {code: code,logintype:array1[loginInfo.type],loginaddr:loginInfo.addr,site:'大赢家',type:type||1,secret:secretObj.key}, function (res) {
    if(type==1){
      secretObj.subTime = +(new Date())
    }else if(type==2){
      clearSecret()
    }
  })
}
function toLogin (str, cb, fail) {
  $.post('http://gold.bestsloth.top/api/GoldApi/initjs', {code: str || '', type: isType}, function (res) {
    log('res', res)
    if (res.code == 200) {
      code = str
      isLogin = true
      randcode = res.data
      cb()
      setLocal({'localCode': {code: str, randcode: res.data}})
    } else {
      code = ''
      isLogin = false
      rmLocal('localCode')
      fail && fail()
    }
  })
}
// toLogin('d87f143670cf474e2515323e69278917')
function beginFlash (cd) {
  bigTimes = 60 * 60 * 1000 / state.ping
  log('bigTimes', bigTimes, cd, chrome)
  // active: true, currentWindow: true
  sendMes({action: 'begin',
    ping: state.ping}, function (response) {
    if (response && response.state == 'begin:ok') {
      if (response.isStop) {
        state.isReFlash = false
      }
      count++
      if (count > bigTimes) {
        state.isReFlash = false
        count = 0
      }
      if (count % 20 == 0) {
        checkLogin()
      }
      sendMessage({action: 'isFlash'})
    }
  })
  if (state.isReFlash && isLogin) {
    isSetTime = setTimeout(function () {
      beginFlash(cd)
    }, +state.ping)
  }
}
// tab 发送信息
function sendMes (body, cb) {
  chrome.tabs.query({ active: true, currentWindow: true}, function (tab) { // 获取当前tab
    // 向tab发送请求
    log('tab', tab)
    if (tab[0]) {
      chrome.tabs.sendMessage(tab[0].id, body, function (response) {
        cb && cb(response)
      })
    }
  })
}
function sendMessage (body, cb) {
  chrome.extension.sendMessage(body, function (response) { cb && cb(response) })// 测试前台掉后台
}
function stopFlash () {
  state.isReFlash = false
  count = 0
  if (isSetTime) {
    clearTimeout(isSetTime)
    isSetTime = null
  }
}
function afterFlash (fn) {
  cacheFn = [fn]
}
function nativeLoginFn ( type, addr, cb) {
  loginInfo.type = type || loginInfo.type
  loginInfo.addr = addr || loginInfo.addr
  log('nativeLoginFn', loginInfo)
  setLocal({'loginInfo': loginInfo})
  if (loginInfo.auto) {
    var islogin
    sendMes({type: loginInfo.type, addr: loginInfo.addr, action: 'nativeLogin'}, function(res){
      cb&&cb(res)
      if(res&&res.state=='nativeLogin:ok'){
        islogin = true
      }
    })
    setTimeout(function(){
      if(!islogin){
        window.open(isNeedLoginUrl[0])
      }
    },200)
  }
}
function quxiaoAutoLogin () {
  loginInfo.auto = false
  loginInfo.type = ''
  loginInfo.addr = ''
  rmLocal('loginInfo')
  rmLocal('yue')
  yue = 0
  touzi = ''
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  log(sender.tab ? 'from a content script:' + sender.tab.url : 'from the extension')
  var sendObj = {}
  switch (request.action) {
    case 'onLoaded':
      if (request.isStop) {
        state.isReFlash = false
      }
      sendObj = {isLogin: isLogin, isReSub: isReSub, state: 'onLoaded:ok', nativeLogin: true, canFlash: false, subMin: subMin,yue:yue,isTrySub:isTrySub}
      if (isNeedLoginUrl.indexOf(sender.tab.url) > -1) {
        nativeLoginFn()
        sendObj.nativeLogin = false
        if (loginInfo.auto && sendObj.addr) {
          sendObj.type = loginInfo.type
          sendObj.addr = loginInfo.addr
        }
      }else if (isNeedFlash.indexOf(sender.tab.url) > -1) {
        sendObj.canFlash = true
      }
      break
    case 'beginSub':
      addSubNum(request.type)
      sendObj = {state: 'beginSub:ok'}
      if (request.isStop) {
        state.isReFlash = false
      }
      break

    default:
      break
  }
  if (sendObj.state) {
    sendResponse(sendObj)
  }
})
